apiready = function() {
    seajs.use(['../../V', "../../api", "../../jquery", "../../app", "../../service", "../../dialog"], function(V, $api, $, $app, service, dialog) {
        var vm = {
            el: '.container',
            data: {
                is_Show: false,
                cartList: '',
                is_plusMinus: false,
                is_cart: false,
                channel: '',
                bs: "" //ajax弹出服务器提示控制变量
            },
            methods: {
                init: function(et) {
                    if ($api.getStorage("user")) {
                        this.bs = 1;
                    } else {
                        this.bs = "";
                    }
                    if (this.bs == "" || this.bs == 'undefined') { //游客模式，没有缓存
                        $('.batch_classfiy').css("display", "block");
                        return;
                    } else {
                        this.getList();
                    }
                },
                classfiySure: function() {
                    api.closeToWin({
                        name: 'WeChat_login'
                    });
                },
                getList: function(et) {
                    var unionid = $api.getStorage("shop_unionid");
                    var self = this;

                    console.log(unionid);
                    $app.ajax(service.getCartList, {
                        data: {
                            values: {
                                unionid: unionid
                            }
                        }
                    }, function(res) {
                        console.log("cart: " + JSON.stringify(res));
                        if (res.code == 0) {
                            self.cartList = res.data;
                            if (self.cartList.length > 0) {
                                // self.$refs.cartNull.style.display = "none";
                                document.querySelector(".cart-null").style.display = "none";
                            } else {
                                self.is_Show = false;
                                document.querySelector("#myCartEdit").innerHTML = '编辑';
                                document.querySelector(".cart-null").style.display = "block";
                                // self.$refs.cartNull.style.display = "block";
                            }
                        }
                    });
                },
                getFather: function(obj, el) {
                    var name = obj;
                    while (name) {
                        if (name.tagName == el) {
                            break;
                        }
                        name = name.parentNode;
                    }
                    return name;
                },
                checked: function(obj, bol) {
                    if (bol) {
                        for (var i = 0; i < obj.length; i++) {
                            if (!obj[i].disabled) {
                                obj[i].checked = true;
                            }
                        }
                    } else {
                        for (var i = 0; i < obj.length; i++) {
                            if (!obj[i].disabled) {
                                obj[i].checked = false;
                            }
                        }
                    }
                },
                checkAll: function(allBol) {
                    if (this.is_Show) {
                        this.$refs.delCartCheckAll.checked = allBol;
                    } else {
                        this.$refs.cartCheckAll.checked = allBol;
                    }
                },
                //--去商品详情
                goGoodsDetail: function(et) {
                    var name = et.target.tagName;
                    if (name == "INPUT" || name == "SELECT" || name == "P" || name == "A" || name == "SPAN") {
                        return;
                    }
                    var goodsId = et.currentTarget.dataset.goodsid;
                    $app.openWin('buyGoods', {
                        goodsId: goodsId
                    });
                },
                //--全选
                cartCheckAll: function(et) {
                    var check = this.$refs.cartList.querySelectorAll("input[type='checkbox']");
                    this.checked(check, et.target.checked);
                    this.sumMoney();
                },
                //--删除,全选
                delCheckAll: function(et) {
                    var check = this.$refs.cartList.querySelectorAll("input[type='checkbox']");
                    this.checked(check, et.target.checked);
                },
                //--取消编辑
                cartCancelEdit: function(et) {
                    var list = document.querySelectorAll("#cartContainer input[type='checkbox']");
                    for (var i = 0; i < list.length; i++) {
                        list[i].checked = false;
                    }
                    document.querySelector("#myCartEdit").innerHTML = '编辑';
                    this.is_Show = false;
                },
                //--店铺选择
                shopCheck: function(et) {
                    var _node = document.querySelector("#cartListli" + et.target.dataset.index).querySelectorAll("input[type='checkbox']");
                    var shopInput = this.$refs.shopInput;
                    this.checked(_node, et.target.checked);
                    if (et.target.checked) {
                        for (var i = 0; i < shopInput.length; i++) {
                            if (!shopInput[i].checked) {
                                this.checkAll(false);
                                break;
                            }
                            if (shopInput[i].checked && i == shopInput.length - 1) {
                                this.checkAll(true);
                            }
                        }
                    } else {
                        this.checkAll(false);
                    }
                    this.sumMoney();
                },
                toShop: function(index){
                  var shop_user_id = this.cartList[index].shop_user_id;
                  $app.openWin('singleShop', {
                      out_user_id: shop_user_id
                  });
                },
                //--商品选择
                goodsCheck: function(et) {
                    var goodsInput = this.$refs.cartList.querySelectorAll("input[type='checkbox']");
                    var oInput = this.getFather(et.target, "LI").querySelectorAll("input[type='checkbox']");
                    if (et.target.checked) {
                        this.checkAll(false);
                        for (var i = 1; i < oInput.length; i++) {
                            if (!oInput[i].checked) {
                                oInput[0].checked = false;
                                this.checkAll(false);
                                break;
                            }
                            if (oInput[i].checked && i == oInput.length - 1) {
                                oInput[0].checked = true;
                                for (var j = 0; j < goodsInput.length; j++) {
                                    if (!goodsInput[j].checked) {
                                        this.checkAll(false);
                                        break;
                                    }
                                    if (goodsInput[j].checked && j == goodsInput.length - 1) {
                                        this.checkAll(true);
                                    }
                                }
                            }

                        }
                    } else {
                        this.checkAll(false);
                        oInput[0].checked = false;
                    }
                    this.sumMoney();
                },
                //--删除商品
                delCartGoods: function(et) {
                    var unionid = $api.getStorage("shop_unionid"),
                        self = this;
                    var goods = this.$refs.goodsChecks;
                    var cart_ids = "",
                        temp_id = [];
                    for (var i = 0; i < goods.length; i++) {
                        if (goods[i].checked) {
                            temp_id.push(goods[i].dataset.cartid);
                        }
                    }
                    cart_ids = temp_id.join(",");
                    if(cart_ids!=""){
                      dialog.alert({
                          title: "",
                          msg: "是否删除这些商品",
                          buttons: ['取消', '确定']
                      }, function(ret) {
                        if(ret.buttonIndex == 2) { //  确认)

                          $app.ajax(service.getCartDelete, {
                              data: {
                                  values: {
                                      unionid: unionid,
                                      cart_ids: cart_ids
                                  }
                              }
                          }, function(res) {
                              if (res.code == 0) {
                                  self.init();
                                  api.sendEvent({
                                      name: 'lisentCart'
                                  });
                              }
                          });
                        }
                      })
                    }else{
                      api.toast({
                        msg: "请选择商品",
                        duration: 2000,
                        location: 'middle'
                      })
                    }


                },
                //--型号选择,更改价格
                selectModel: function(et) {
                    var unionid = $api.getStorage("shop_unionid"),
                        self = this;
                    var el = et.currentTarget;
                    var _change = el.value.split(",");
                    var cart_id = et.currentTarget.parentNode.dataset.cartid || "";
                    var option_id = _change[0] || "";
                    el.parentNode.querySelectorAll("span")[0].innerHTML = "¥" + _change[2];
                    if (cart_id == "" || option_id == "") {
                        return;
                    }
                    $app.ajax(service.cartModOption, {
                        data: {
                            values: {
                                unionid: unionid,
                                cart_id: cart_id,
                                option_id: option_id,
                                mask: 'none'
                            }
                        }
                    }, function(res) {
                        self.init();
                    });
                },
                //--数量更改
                plusMinuAjax: function(id, num, callback) {
                    var unionid = $api.getStorage("shop_unionid"),
                        self = this;
                    var cart_id = id || 0,
                        quantity = num || 0;
                    $app.ajax(service.cartModNumber, {
                        data: {
                            values: {
                                unionid: unionid,
                                cart_id: cart_id,
                                quantity: quantity,
                                mask: 'none'
                            }
                        }
                    }, function(res) {
                        //console.log("modify: "+JSON.stringify(res));
                        if (res.code == 0) {
                            callback(true);
                        } else {
                            callback(false);
                        }
                        self.is_plusMinus = false;
                    });
                },
                //--价钱总数，计算已选择的商品总的金钱
                sumMoney: function() {
                    var goods = this.$refs.goodsChecks;
                    var sum = 0;
                    for (var i = 0; i < goods.length; i++) {
                        if (goods[i].checked && !goods[i].disabled) {
                            var _n = +goods[i].parentNode.querySelectorAll("input[type='text']")[0].value;
                            var _p = +goods[i].dataset.price;
                            sum += _n * _p;
                        }
                    }
                    if (sum == "") {
                        sum = "0.00";
                    } else {
                        sum = sum.toFixed(2);
                    }
                    this.$refs.showSumMoney.innerHTML = "¥" + sum;
                },
                //--加，更改数量
                plusMinusPlus: function(et) {
                    if (this.is_plusMinus || document.querySelector("#goodsSelect" + et.currentTarget.dataset.index) == null) {
                        return;
                    }
                    this.is_plusMinus = true;
                    var _sel = document.querySelector("#goodsSelect" + et.currentTarget.dataset.index).value.split(",");
                    var _input = et.target.parentNode.querySelectorAll("input")[0];
                    var _val = +_input.value;
                    var _ity = +_sel[1];
                    var _id = +et.currentTarget.parentNode.dataset.cartid;
                    var _num = _ity >= _val + 1 ? _val + 1 : _val;
                    var self = this;
                    if (_ity == _val + 1 || _ity == _val) {
                        et.currentTarget.style.color = "#ccc";
                    } else {
                        et.currentTarget.style.color = "#333";
                    }
                    this.plusMinuAjax(_id, _num, function(bol) {
                        if (bol) {
                            if (_ity >= _val + 1) {
                                _input.value = _val + 1;
                            }
                            self.sumMoney();
                        }
                    });
                },
                //--减，更改数量
                plusMinusPlusMinus: function(et) {
                    if (this.is_plusMinus || document.querySelector("#goodsSelect" + et.currentTarget.dataset.index) == null) {
                        return;
                    }
                    et.target.parentNode.children[2].style.color = '#333';
                    this.is_plusMinus = true;
                    var _sel = document.querySelector("#goodsSelect" + et.currentTarget.dataset.index).value.split(",");
                    var _input = et.target.parentNode.querySelectorAll("input")[0];
                    var _val = +_input.value;
                    var _ity = +_sel[1];
                    var _id = +et.currentTarget.parentNode.dataset.cartid;
                    var _num = _val - 1 > 0 ? _val - 1 : _val;
                    var self = this;
                    if (_val - 1 == 0) {
                        return;
                    }
                    this.plusMinuAjax(_id, _num, function(bol) {
                        if (bol) {
                            if (_val - 1 > 0) {
                                _input.value = _val - 1;
                            }
                            self.sumMoney();
                        }
                    });
                },
                //--输入，，更改数量
                plusMinusInput: function(et) {
                    if (this.is_plusMinus || et.currentTarget.value == '' || document.querySelector("#goodsSelect" + et.currentTarget.dataset.index) == null) {
                        return;
                    }
                    this.is_plusMinus = true;
                    var _event = et.target;
                    var _sel = document.querySelector("#goodsSelect" + et.currentTarget.dataset.index).value.split(",");
                    var val = et.target.value.replace(/\s+/, "");
                    var num = +et.target.dataset.num;
                    var _n = /^[0-9]+$/.test(val) ? +val : num;
                    var _ity = +_sel[1];
                    var _id = +et.currentTarget.parentNode.dataset.cartid;
                    var _num = _n > _ity ? _ity : _n == 0 ? num : _n;
                    var self = this;
                    if (_n >= _ity) {
                        et.target.parentNode.children[2].style.color = '#ccc';
                    } else {
                        et.target.parentNode.children[2].style.color = '#333';
                    }
                    this.plusMinuAjax(_id, _num, function(bol) {
                        if (bol) {
                            if (_n > _ity) {
                                _event.value = _ity;
                            } else {
                                _event.value = _n == 0 ? num : _n;
                            }
                            self.sumMoney();
                        }
                    });
                },
                //--结算，生成订单
                generateOrder: function(et) {
                    var li = this.$refs.goodsChecks;
                    var cart_ids = [];
                    for (var i = 0; i < li.length; i++) {
                        if (li[i].checked) {
                            cart_ids.push(li[i].dataset.cartid);
                        }
                    }
                    if (cart_ids.length <= 0) {
                        api.toast({
                            msg: "你没有选择任何商品，请选择",
                            duration: 2000,
                            location: 'middle'
                        });
                        return;
                    }
                    $app.openWin("buyOrder", {
                        cart_ids: cart_ids.join(",")
                    });
                }
            },
            mounted: function() {
                var self = this;
                this.is_cart = api.winName == 'buyCart' ? true : false;
                // $app.refreshHeaderInfo(function() {
                //     self.init();
                // }, 0);
                document.querySelector("#myCartEdit").addEventListener("click", function() {
                    var list = document.querySelectorAll("#cartContainer input[type='checkbox']");
                    if (cartList == '' || cartList.length <= 0) {
                        return;
                    }
                    for (var i = 0; i < list.length; i++) {
                        list[i].checked = false;
                    }
                    if (!self.is_Show && self.cartList != '') {
                        this.innerHTML = '完成';
                        self.is_Show = true;
                    } else {
                        this.innerHTML = '编辑';
                        self.is_Show = false;
                    }
                });
                api.addEventListener({
                    name: 'payBackCart_'
                }, function() {
                    self.init();
                });

                api.addEventListener({
                    name: 'orderInit_'
                }, function() {
                    self.init();
                })

                api.addEventListener({
                    name: 'lisentCart'
                }, function() {
                    self.init();
                });

                api.addEventListener({
                    name: 'keyboardshow'
                }, function(ret, err) {
                    $('.header').css({
                        'top': 0,
                        'position': 'static'
                    });
                });

                api.addEventListener({
                    name: 'keyboardhide'
                }, function(ret, err) {
                    $('.header').css({
                        'top': 0,
                        'position': 'fixed'
                    });
                });

                //--返回个人中心
                function btnKeyBack() {
                    api.sendEvent({
                        name: 'orderBackperson_'
                    });
                    $api.setTimeout(function() {
                        api.closeWin();
                    }, 300);
                }
                //--点击上面按钮返回
                $api.addEvt($api.dom('#btn-back'), 'click', function() {
                    api.closeWin();
                });

                //--返回键
                api.addEventListener({
                    name: 'keyback'
                }, function(ret, err) {
                    api.closeWin();
                });

            },
            created: function() {
                this.init();
                if (api.pageParam.channel) {
                    this.channel = api.pageParam.channel;
                    console.log(this.channel);
                }

            }
        };
        var even = function() {}
        var newVue = new Vue(vm);
        even();
    })
}
